package com.yuji.aacar.net.convertfactory;

import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.yuji.aacar.net.bean.HttpCoreBaseRequest;
import com.yuji.aacar.net.bean.HttpCoreRequestHeader;
import com.yuji.aacar.net.config.BlueLog;
import com.yuji.aacar.net.config.HttpConfig;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * <li>Package:consumer.ttpc.com.httpmodule.converterfactory
 * <li>Author: yehaijian
 * <li>Date: 2017/6/7
 * <li>Description:
 */
public class JsonBase64RequestConverter<T> extends JsonRequestBodyConverter<T> {

    /**
     * 构造器
     *
     * @param gson
     * @param adapter
     * @param code
     */
    public JsonBase64RequestConverter(Gson gson, TypeAdapter adapter, int code) {
        super(gson, adapter, code);
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        int code =0;
        if(value instanceof HttpCoreBaseRequest){
            code=this.code!=0?this.code:((HttpCoreBaseRequest) value).getRequestCode();
        }
        HttpCoreRequestHeader head = new HttpCoreRequestHeader(code);
        //将最终bean生成json串
        String bodyJson = gson.toJson(value, new TypeToken<T>() {
        }.getType());
        String headerJson = gson.toJson(head, new TypeToken<HttpCoreRequestHeader>() {
        }.getType());
        BlueLog.e("request", "request body## ：" + code + " " + bodyJson);
        BlueLog.e("request", "request header## ：" + code + " " + headerJson);

        String postBody = new String(Base64.encode(bodyJson.getBytes(), Base64.NO_WRAP));
        String postHeader =new String(Base64.encode(headerJson.getBytes(), Base64.NO_WRAP));

        BlueLog.e("request", "requestBase64 body## ：" + code + " " + postBody);
        BlueLog.e("request", "requestBase64 header## ：" + code + " " + postHeader);

        FormBody.Builder builder = new FormBody.Builder();
        FormBody formBody = value instanceof HttpCoreBaseRequest ?
                builder.addEncoded("info", postBody).addEncoded("Ttp", postHeader).addEncoded(HttpConfig.IS_WEBVIEW, ((HttpCoreBaseRequest) value).isWebView() + "")
                        .build() :
                builder.addEncoded("info", postBody).addEncoded("Ttp", postHeader)
                        .build();
        return formBody;
    }
}